package com.infore.operation.service.impl;

import java.io.File;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.infore.operation.entity.AttendanceInfo;
import com.infore.operation.entity.AttendanceRule;
import com.infore.operation.entity.Image;
import com.infore.operation.entity.Inspect;
import com.infore.operation.entity.Person;
import com.infore.operation.entity.ReportImge;
import com.infore.operation.entity.RstImage;
import com.infore.operation.entity.UserInfoId;
import com.infore.operation.entity.WorkType;
import com.infore.operation.entity.reportDetil;
import com.infore.operation.mapper.AttendanceMapper;
import com.infore.operation.mapper.UserMapper;
import com.infore.operation.service.PunchtheService;
import com.infore.operation.service.UserService;
import com.infore.operation.utils.FileUtil;
import com.infore.operation.utils.FormatUtil;
import com.infore.operation.utils.UUIDGenerator;

@Service
public class PunchtheServiceImpl implements PunchtheService {
	@Autowired
	private AttendanceMapper attendanceMapper;
	@Autowired
	private UserMapper userMapper;
	@Value("${imagePath}")
	private String imagePath;
	@Value("${photoPath}")
	private String photoPath;

	@Override
	public String saveAttendace(AttendanceInfo info, MultipartFile[] imges,Integer supplement) {
	    String time =info.getAttendanceTime().split(" ")[0];
	    List<AttendanceInfo> infos  =attendanceMapper.queryDayAttendanceRecords(info.getCreatePeopleId(), time);
	    if(supplement!=1) {
	    if(infos.size()==1&&info.getAttendanceType()==0) {
	        return "上班卡已打";
	    }
	    if(infos.size()==2&&info.getAttendanceType()==1) {
	        return "下班卡已打";
	    }
	    String uuid = UUIDGenerator.randomUUID();
	    info.setAttendanceId(uuid);
	   
	    }
	    String createTime = FormatUtil.secondG.format(new Date());
       
		info.setCreateTime(createTime);
		// 新增图片
		Integer imageNum=0;
		if (imges != null && imges.length != 0) {
			info.setAttendancePhoto(1);
			List<ReportImge> list = new ArrayList<>();
			for (int i = 0; i < imges.length; i++) {
				ReportImge image = new ReportImge();
				File fileDir = new File(photoPath + "//attendance");
				try {
					FileUtil.judeFileExists(fileDir);
					String name = FormatUtil.getUUID()
							+ imges[i].getOriginalFilename().substring(imges[i].getOriginalFilename().lastIndexOf("."));
					FileUtil.createFile(photoPath + "//attendance", imges[i].getBytes(), name);
					image.setLocal(photoPath + "//attendance//" + name);
					image.setName(imges[i].getOriginalFilename());
					image.setUuid(UUIDGenerator.randomUUID());
					image.setReportId(info.getAttendanceId());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				list.add(image);
			}
			imageNum = attendanceMapper.saveReportImage(list);
		}
		// 取出打卡规则
		AttendanceRule rule = attendanceMapper.queryRule();
		//放入上下班时间
		if(info.getAttendanceType()==0) {
            info.setStandardTimes(rule.getWorkOn());
        }else {
            info.setStandardTimes(rule.getWorkOff());
        }
		//判断提交日报时的状态
		//判断是否为补卡
		 
		if(supplement==1) {
	        Map<String, Object> attendance = attendanceMapper.querySupplementPunch(info.getCreatePeopleId());
	        Integer numss=rule.getSupplementUpperLimit() - (Integer) attendance.get("num");
	        if(numss<0||numss==0) {
	            return "补卡次数已用完";
	        }
            info.setAddAttendanceId(4);
            info.setAddAttendanceName("补卡");
           
            Integer num = attendanceMapper.updateAttendanceInfo(info);
    		return "";
		}
		try {
			Time ruleOn=rule.getWorkOn();//取出上班时间
			Time ruleup=rule.getWorkOff();//取出下班时间
			String work=info.getAttendanceTime().split(" ")[1];
			SimpleDateFormat simple =new SimpleDateFormat("HH:mm:ss");
			Date workOnTime=simple.parse(work);
		//判断上班是否迟到
		if(info.getAttendanceType()==0) {
		if(ruleOn.before(workOnTime)) {
			info.setAddAttendanceId(2);
			info.setAddAttendanceName("迟到");
			
		}else {
			info.setAddAttendanceId(1);
			info.setAddAttendanceName("正常");
		}
		
		}
		//判断下班是否早退
		if(info.getAttendanceType()==1) {
			if(ruleup.after(workOnTime)) {
				info.setAddAttendanceId(3);
				info.setAddAttendanceName("早退");
				
			}else {
				info.setAddAttendanceId(1);
				info.setAddAttendanceName("正常");
			}
			}
		Integer num = attendanceMapper.saveAttendanceInfo(info);
		return "";
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public String saveReport(Map<String, Object> map, MultipartFile[] imges, String linkId) {
		String result = "";
		List<Map<String,Object>>reportDay=attendanceMapper.queryDayReportInfo((Integer) map.get("userId"),(String) map.get("targetDate"));
		if(reportDay!=null&&reportDay.size()!=0) {
			return "已提交目标日期日报";
		}
		String reportId = UUIDGenerator.randomUUID();
		map.put("detailId", reportId);
		Integer imageNum = 0;
		// 新增图片
		if (imges != null && imges.length != 0) {
			map.put("photo", 1);
			List<ReportImge> list = new ArrayList<>();
			for (int i = 0; i < imges.length; i++) {
				ReportImge image = new ReportImge();
				File fileDir = new File(photoPath + "//Report");
				try {
					FileUtil.judeFileExists(fileDir);
					String name = FormatUtil.getUUID()
							+ imges[i].getOriginalFilename().substring(imges[i].getOriginalFilename().lastIndexOf("."));
					FileUtil.createFile(photoPath + "//Report", imges[i].getBytes(), name);
					image.setLocal(photoPath + "//Report//" + name);
					image.setName(imges[i].getOriginalFilename());
					image.setUuid(UUIDGenerator.randomUUID());
					image.setReportId(reportId);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				list.add(image);

			}
			imageNum = attendanceMapper.saveReportImage(list);
			if (imageNum == null || imageNum == 0){
				result += "图片提交失败";
			}
		}
		if (linkId != null && !linkId.equals("")) {
			
			String[]linkIdss=linkId.split(",");
			List linkIds = new ArrayList<>(Arrays.asList(linkIdss));
			Map<String, Object> Inspect = new HashMap<String, Object>();
			Inspect.put("reportId", reportId);
			Inspect.put("linkIds", linkIds);
			Integer linkedId = attendanceMapper.saveReportLinkId(Inspect);
			if (linkedId == null || linkedId == 0) {
				result += "巡检关联失败";
			}
		}
		Integer reportNum = attendanceMapper.saveReport(map);
		
		if (reportNum == null || reportNum == 0) {
			result += "日报提交失败";
		}
		return result;
	}

	public List<WorkType> queryworkTypes() {
		List<WorkType> workTypes = attendanceMapper.queryWorkType();
		return workTypes;
	}

	@Override
	public List<Map<String, Object>> queryinspectionRecords(Integer userId, String date) {
		List<Map<String, Object>> inspects = attendanceMapper.queryinspectionRecords(userId, date);
		return inspects;
	}

	@Override
	public List<reportDetil> queryReports(String date, Integer range, Integer userId, Integer pageNum) {
		String postName = (String) userMapper.queryUserInfo(userId).get("post");
		// 查询下属日报时获取当天的，查询个人的时候没有时间限制分页查询
		PageHelper.startPage(pageNum + 1, 20);
		// 分页查出日报当天信息
		List<reportDetil> reports = attendanceMapper.queryReports(range, postName, userId, date);
		for (reportDetil report : reports) {
			// 查询和日报相关的巡检信息
			System.out.println(report.getReportId());
			report.setLinkInspection(attendanceMapper.queryinspectionRecordByreportId(report.getReportId()));
			;

			// 查询和日报相关的图片信息
			List<String> images = attendanceMapper.queryImageByReportId(report.getReportId());
			String image = String.join(",", images);
			image = image.replace(photoPath, "http://" + imagePath);
			image = image.replace("\\", "/");
			report.setImage(image);

			// 将头像转化为图片
			String url = FileUtil.getFile(report.getHeadImages(), photoPath + "//headImage",
					report.getUserId() + ".png");
			String headImg ="";
			if(url!=null) {
			 headImg = url.replace(photoPath, "http://" + imagePath);
			headImg = headImg.replace("\\", "/");
			}
			report.setHeadImage(headImg);
			report.setHeadImages(null);
			// 查询和日报相关的审核信息
			List<Map<String, Object>> audit = attendanceMapper.queryAuditByreport(report.getTargetDate(),
					report.getUserId());
			System.out.println(audit.size() != 0);
			if (audit != null && audit.size() != 0) {
				report.setConfirm(1);
			} else {
				report.setConfirm(0);
			}
		}
		return reports;
	}

	@Override
	public Map<String, Object> queryReportTypeStatistics(String startTime, String endTime, Integer userId,
			Integer range) {
		String postName = (String) userMapper.queryUserInfo(userId).get("post");
		Integer num = 0;
		Integer total = 0;
		if (range == 1) {
			num = (Integer) attendanceMapper.queryTotalReportUnderLow(userId, postName, range, startTime, endTime)
					.get("num");
			total = (Integer) attendanceMapper.queryTotalPsonUnderlow(userId, postName).get("num");
		} else if (range == 0) {
			total = attendanceMapper.queryTotalAttendance(startTime, endTime,userId).size();
			num = (Integer) (attendanceMapper.queryTotalReportUnderLow(userId, postName, range, startTime, endTime)
					.get("num"));
		}
		List<Map<String, Object>> reportTypeStatistics = attendanceMapper.queryReportTypeStatistics(userId, startTime,
				endTime, range, postName);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("shouldSubmit", total);
		map.put("realSubmit", num);
		map.put("typeStatistics", reportTypeStatistics);
		if(total-num<0) {
		map.put("missing", 0);
		}else{
		map.put("missing", total-num);
		}
		
		return map;
	}

	/**
	 * 查询日报月度提交状态统计
	 * 
	 * @param userId
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	@Override
	public List<Map<String, Object>> queryReportSubmissionStateStatistics(Integer userId, String startTime,
			String endTime) {
		List<Map<String, Object>> reportSubmissionStateStatistics = attendanceMapper
				.queryReportSubmissionStateStatistics(endTime, startTime, userId);
		for (Map<String, Object> map : reportSubmissionStateStatistics) {
			if (map.get("reportId") != null  && !map.get("reportId").equals("0") && map.get("reportId")!="0" ) {
				map.put("commit", 1);
			} else {
				map.put("commit", 0);
			}
		}
		return reportSubmissionStateStatistics;
	}

	@Override
	public List<Map<String, Object>> queryPowerReportInfo(String date, Integer userId) {
		String postName = (String) userMapper.queryUserInfo(userId).get("post");
		Date time = null;
		try {
			time = FormatUtil.historymonth.parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 根据月份得出第一天和最后一天
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(time);
		String startTime = date + "-01";
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
		String endTime = FormatUtil.secondA.format(calendar.getTime());
		List<Map<String, Object>> powerReportInfo = attendanceMapper.queryPowerReportInfo(startTime, endTime, userId,
				postName);
		return powerReportInfo;
	}

	@Override
	public Integer deleteReportId(String reportId) {
		Integer num = attendanceMapper.deleteReport(reportId);
		return num;
	}

	@Override
	public AttendanceRule queryRule(Integer userId) {
		AttendanceRule rule = attendanceMapper.queryRule();
		Map<String, Object> attendance = attendanceMapper.querySupplementPunch(userId);
		rule.setResidueSupplement(rule.getSupplementUpperLimit() - (Integer) attendance.get("num"));
		return rule;
	}

	@Override
	public List<AttendanceInfo> queryDayAttendanceRecords(Integer userId, String date) {
		List<AttendanceInfo> info = attendanceMapper.queryDayAttendanceRecords(userId, date);
		for (AttendanceInfo attendanceInfo : info) {
            AttendanceRule rule =attendanceMapper.queryRule();
              Time ruleOff=attendanceInfo.getStandardTimes();
             if(ruleOff!=null) {
             Date rOff = FormatUtil.timeToDate(ruleOff);
             SimpleDateFormat simple =new SimpleDateFormat("HH:mm:ss");
             String off=simple.format(rOff);
              attendanceInfo.setStandardTime(off);
             }
			if (attendanceInfo.getAttendancePhoto() != null && attendanceInfo.getAttendancePhoto() == 1) {
				// 查询和考勤相关的图片信息
				List<String> images = attendanceMapper.queryImageByReportId(attendanceInfo.getAttendanceId());
				String image = String.join(",", images);
				image = image.replace(photoPath, "http://" + imagePath);
				image = image.replace("\\", "/");
				attendanceInfo.setImages(image);
			}
		}
		return info;
	}

	@Override
	public Map<String, Object> queryMonthTabulateStatistics(Integer userId, String startDate, String endDate) {
		   Map<String, Object> map= new HashMap<String, Object>();
		   //考勤时间统计
		   map.put("attendanceDays", attendanceMapper.queryAbsenteeismDays(userId, 1, startDate, endDate));//正常打卡日期
		   map.put("lateTimes", attendanceMapper.queryMonthTabulateStatistics(userId, 2, startDate, endDate));//迟到打卡
		   map.put("earlyTimes",  attendanceMapper.queryMonthTabulateStatistics(userId, 3, startDate, endDate));//早退打卡
		   map.put("lackTimes",attendanceMapper.queryMonthTabulateStatistics(userId, 5, startDate, endDate));//缺卡
		   map.put("absenteeismDays", attendanceMapper.queryAbsenteeismDays(userId, 5, startDate, endDate));//旷工
		return map;
	}

	@Override
	public List<Map<String, Object>> queryMonthStatusStatistics(Integer userId, String startDate, String endDate) {
		List<Map<String,Object>>list=attendanceMapper.queryMonthStatusStatistics(userId,startDate,endDate);
		return list;
	}

	@Override
	public List<Map<String, Object>> queryMonthUnderlingTabulateStatistics(Integer userId, String startDate,
			String endDate, Integer pageNum) {
		UserInfoId userInfoId=userMapper.queryUserInfoId(userId+"");
		Integer brid=userInfoId.getBranchId();
		Integer opId=userInfoId.getOpId();
		Integer postId=userInfoId.getPostId();
		PageHelper.startPage(pageNum + 1, 20);
		List<Person> per=userMapper.queryLowPson(opId, userId, postId, brid, null);
		List<Map<String, Object>>list =new ArrayList<Map<String, Object>>();
		for (Person person : per) {
			Map<String, Object> map= new HashMap<String, Object>();
			   //考勤时间统计
			   map.put("userId", person.getId());
			   map.put("userName",person.getName());
			   map.put("postName",person.getLevelName());
				// 将头像转化为图片
				String url = FileUtil.getFile(userMapper.getLoginUserByAccount(person.getName()).getPicImg(), photoPath + "//headImage",
						 person.getId() + ".png");
				String headImg ="";
				if(url!=null) {
				 headImg = url.replace(photoPath, "http://" + imagePath);
				headImg = headImg.replace("\\", "/");
				}
			   map.put("headImg", headImg);
			   map.put("attendanceDays", attendanceMapper.queryAbsenteeismDays(person.getId(), 1, startDate, endDate).size());//正常打卡
			   map.put("lateTimes", attendanceMapper.querycountMonthTabulateStatistics(person.getId(), 2, startDate, endDate));//迟到打卡
			   map.put("earlyTimes",  attendanceMapper.querycountMonthTabulateStatistics(person.getId(), 3, startDate, endDate));//早退打卡
			   map.put("lackTimes",attendanceMapper.querycountMonthTabulateStatistics(person.getId(), 5, startDate, endDate));//缺卡
			   map.put("absenteeismDays", attendanceMapper.queryAbsenteeismDays(person.getId(), 5, startDate, endDate).size());//旷工
			   list.add(map);
		}
		return list;
	}

}
